#coding:utf-8
"""

""" 
import urllib
import time
import hmac
import hashlib
import base64
import random
from http_client import http_client
from http_client import ErrorRespon
from urllib import quote
import sys

import webbrowser
import pprint

pp = pprint.PrettyPrinter(indent=4)
def log(d,name=None):
    if name:
        print()
        print("="*10+name+"="*10)
    pp.pprint(d)
    print()
    
def to_str(x):
    '''转换为utf8编码'''
    return  x.decode(sys.stdin.encoding).encode('utf-8')

class SortedDisplayDict(dict):
    def __str__(self):
        return "{" + ", ".join("%r: %r" % (key, self[key]) for key in sorted(self)) + "}"

 

class KuaipanSession():
    API_VERSION   = 1
    API_HOST      = "https://openapi.kuaipan.cn"
    CONTENT_HOST  = "api-content.dfs.kuaipan.cn"
    CONV_HOST     = "conv.kuaipan.cn"
    AUTH_HOST     = "https://www.kuaipan.cn/api.php?ac=open&op=authorise&oauth_token="
    debug = False
    
    def __init__(self, consumer_key, consumer_secret,access_type):
        self.consumer_key   =consumer_key;
        self.consumer_secret=consumer_secret;
        self.oauth_token=""
        self.oauth_token_secret=""
        assert access_type in ['kuaipan', 'app_folder']
        self.root = access_type
        
    def request(self, host, target, params = None, security = False):
        
        url=self.build_url(host, target, params)
      
        ret = http_client.GET(url)
        return ret
 
    def set_oauth_token(self,oauth_token,oauth_token_secret):
        self.oauth_token        = oauth_token
        self.oauth_token_secret = oauth_token_secret
        
    def request_token(self, callback = None):
        ''' 获取临时的oauth_token
        ''' 
        ret = self.request(self.API_HOST,'/open/requestToken',None)
        self.log(ret)
        self.set_oauth_token(ret['oauth_token'] ,ret['oauth_token_secret'].encode('utf-8'))
 
    def _get_oauth_url(self):
        return self.AUTH_HOST+self.oauth_token
        
    def _access_token(self, code = None):
        ''' 获取真正的oauth_token
        '''
        params={}
        if code:
            params['oauth_verifier'] =code
        ret=  self.request(self.API_HOST,'/open/accessToken',params)
        self.set_oauth_token(ret['oauth_token'] ,ret['oauth_token_secret'].encode('utf-8'))
        self.log( ret )
        return ret


    def build_url(self, host, target, params = None ,http_method ='GET'):
        '''生成签名后的链接地址'''
        args=self.get_oauth_params()
        if params is not None:
            args.update(params)
        base_url=self.build_path(host,target,False)
        
        #签名
        _signature=self.signature(base_url,args,http_method)
        args['oauth_signature']=_signature
        url=base_url+'?'+urllib.urlencode(args)
        self.log(url,'request url')
        self.log(args, 'params')
        return url
        
    def build_path(self, host, target, security):
        '''生成base_url
        '''
        target = to_str(target)
        target_path = quote(target)
        if not host.startswith(("http://", "https://")):
            schema = "https://" if security else "http://"
        else:
            schema = ""
        return schema + host + target_path
        
    def get_oauth_params(self):
        '''通用oauth参数
        '''
        params={}
        params["oauth_consumer_key"]     =self.consumer_key
        params["oauth_signature_method"] ="HMAC-SHA1"
        params["oauth_timestamp"]        = str(int(time.time()))
        params["oauth_nonce"]            = str(int(time.time()))+str(random.randint(100,999)) #13
        if self.oauth_token is not "":
            params["oauth_token"]=self.oauth_token
        params['oauth_version']          ='1.0'
        return params
        
    def signature(self,base_url,params,httpMethod="GET"):
        '''签名'''
       
        queryString=[urllib.quote(k,safe='')+"="+urllib.quote(v,safe='') for k,v in params.items()]
        queryString.sort()
        baseStr="%s&%s&%s" % (httpMethod, urllib.quote(base_url,safe=""),
                                urllib.quote("&".join(queryString), safe=""))
 
        s2=self.consumer_secret+"&"+self.oauth_token_secret
 
        myhmac=hmac.new(s2,digestmod=hashlib.sha1)
        myhmac.update(baseStr)
        
        signatureValue=base64.encodestring(myhmac.digest()).strip()
        return signatureValue
        
    def get_oauth_token(self):
        """调用浏览器获取"""
        self.request_token()
        url=self._get_oauth_url()
        #打开浏览器
        webbrowser.open(url)
        print('open url and get oauth code')
        print(url)
        while True:
            code=raw_input("Press Enter after oauthed  \n");
            try:
                return self._access_token()
            except ErrorRespon as e:
                print(e.code,e.reason )
    
    def log(self,msg,name=None):
        if self.debug:
            log(msg,name)

if __name__ == "__main__":
    pass 
    